// 颜色工具函数
export const colorUtils = {
  // 解析各种颜色格式到 RGBA
  parseColor(color: string): [number, number, number, number] {
    // 处理 rgba 格式
    const rgbaMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/)
    if (rgbaMatch) {
      return [parseInt(rgbaMatch[1]), parseInt(rgbaMatch[2]), parseInt(rgbaMatch[3]), rgbaMatch[4] ? parseFloat(rgbaMatch[4]) : 1]
    }

    // 处理 hex 格式 (#ffffff 或 #fff)
    const hexMatch = color.match(/^#([a-f\d]{3,6})$/i)
    if (hexMatch) {
      const hex = hexMatch[1]
      if (hex.length === 3) {
        // 短格式 #fff -> #ffffff
        return [parseInt(hex[0] + hex[0], 16), parseInt(hex[1] + hex[1], 16), parseInt(hex[2] + hex[2], 16), 1]
      } else {
        return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16), 1]
      }
    }

    // 处理 hsl 格式
    const hslMatch = color.match(/hsla?\((\d+),\s*(\d+)%,\s*(\d+)%(?:,\s*([\d.]+))?\)/)
    if (hslMatch) {
      const h = parseInt(hslMatch[1]) / 360
      const s = parseInt(hslMatch[2]) / 100
      const l = parseInt(hslMatch[3]) / 100
      const a = hslMatch[4] ? parseFloat(hslMatch[4]) : 1

      const [r, g, b] = this.hslToRgb(h, s, l)
      return [r, g, b, a]
    }

    // 默认返回白色
    console.warn(`无法解析颜色: ${color}，使用默认白色`)
    return [255, 255, 255, 1]
  },

  // HSL 到 RGB 转换
  hslToRgb(h: number, s: number, l: number): [number, number, number] {
    let r, g, b

    if (s === 0) {
      r = g = b = l // 无饱和度时为灰色
    } else {
      const hue2rgb = (p: number, q: number, t: number) => {
        if (t < 0) t += 1
        if (t > 1) t -= 1
        if (t < 1 / 6) return p + (q - p) * 6 * t
        if (t < 1 / 2) return q
        if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
        return p
      }

      const q = l < 0.5 ? l * (1 + s) : l + s - l * s
      const p = 2 * l - q
      r = hue2rgb(p, q, h + 1 / 3)
      g = hue2rgb(p, q, h)
      b = hue2rgb(p, q, h - 1 / 3)
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
  },

  // 检查是否为渐变色
  isGradient(color: string): boolean {
    return /linear-gradient|radial-gradient|conic-gradient/i.test(color)
  },

  // 颜色插值
  interpolateColor(startColor: string, endColor: string, progress: number): string {
    const [r1, g1, b1, a1] = this.parseColor(startColor)
    const [r2, g2, b2, a2] = this.parseColor(endColor)

    const r = Math.round(r1 + (r2 - r1) * progress)
    const g = Math.round(g1 + (g2 - g1) * progress)
    const b = Math.round(b1 + (b2 - b1) * progress)
    const a = a1 + (a2 - a1) * progress

    return `rgba(${r}, ${g}, ${b}, ${a})`
  },

  // 格式化为 RGBA 字符串
  toRgbaString(r: number, g: number, b: number, a: number): string {
    return `rgba(${r}, ${g}, ${b}, ${a})`
  },
}
